package com.edt.ichannel.api.service.impl;

import cc.edt.iceutils2.string.IceStringUtils;
import cc.edt.iceutils3.date.IceDateFormatUtils;
import cc.edt.iceutils3.json.IceFastJsonUtils;
import cc.edt.iceutils3.wechat.error.bean.ErrorInfo;
import cc.edt.iceutils3.wechat.template.IceWeChatTemplateUtils;
import cc.edt.iceutils3.wechat.template.bean.*;
import com.alibaba.fastjson.JSON;
import com.edt.ichannel.api.common.constant.CommonConstant;
import com.edt.ichannel.api.common.entity.ActionResult;
import com.edt.ichannel.api.entiy.local.WechatTemplate;
import com.edt.ichannel.api.service.EdtApiService;
import com.edt.ichannel.api.service.InterfaceLogService;
import com.edt.ichannel.api.service.WechatService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 李爽
 * @date 2018/3/8 13:36
 */
@Service
public class WechatServiceImpl implements WechatService {
    @Resource
    private EdtApiService edtApiService;
    private static final String SEND_SUCCESS = "0";
    private Logger logger = LogManager.getLogger(WechatServiceImpl.class);
    @Resource
    private InterfaceLogService interfaceLogService;

    @Async
    @Override
    public void sendTemplateMessage(String money, String fee, String openId, boolean isSuccess, String resultMessage) {
        ActionResult actionResult = new ActionResult();
        WechatTemplate wechatTemplate = null;
        try {
            logger.info("推送模板消息：");
            //推送微信模板消息
            DecimalFormat df=new DecimalFormat("0.00");
            String amount=df.format((float)(Integer.parseInt(money)-Integer.parseInt(fee))/100);
            wechatTemplate = templateMsg(openId, isSuccess,amount,new Date(),resultMessage);
            if(wechatTemplate != null){
                actionResult = sendTemplateMessage(wechatTemplate);
            }else{
                actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                actionResult.setMessage("生成模板消息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("模板消息异常："+e.getMessage());
            actionResult.setSuccess(false);
            actionResult.setMessage("模板消息异常："+e.getMessage());
        }finally {
            interfaceLogService.addLog(actionResult, IceFastJsonUtils.toJsonString(wechatTemplate), "/weChat/sendTemplateMessage", CommonConstant.INTERFACE_TYPE_SENDWECHATTEMPLATE);
        }

    }

    @Override
    public ActionResult sendTemplateMessage(WechatTemplate wechatTemplate) {
        ActionResult actionResult = new ActionResult();
        try {
            logger.info("模板消息："+IceFastJsonUtils.toJsonString(wechatTemplate));
            boolean b = IceStringUtils.isAnyBlank(wechatTemplate.getOpenId(), wechatTemplate.getAppId());
            if (b) {
                actionResult.setSuccess(false);
                actionResult.setMessage("openid或appid 不允许为空");
            }else{
                String accessToken = edtApiService.getAccessToken(wechatTemplate.getAppId());
                if (IceStringUtils.isBlank(accessToken)) {
                    actionResult.setSuccess(false);
                    actionResult.setMessage("获取access_token失败");
                }else{
                    Template template = new Template();
                    template.setOpenId(wechatTemplate.getOpenId());
                    template.setTemplateId(wechatTemplate.getTemplateId());
                    template.setUrl(wechatTemplate.getUrl());
                    TemplateContent templateContent = new TemplateContent();
                    templateContent.setFirst(wechatTemplate.getFirst());
                    templateContent.setListKeyWord(wechatTemplate.getListKeyWord());
                    templateContent.setRemark(wechatTemplate.getRemark());
                    template.setTemplateContent(templateContent);
                    ErrorInfo errorInfo = IceWeChatTemplateUtils.sendTemplate(accessToken, template);
                    if (SEND_SUCCESS.equals(errorInfo.getErrCode())) {
                        actionResult.setSuccess(true);
                        actionResult.setMessage(errorInfo.getErrMsg());
                    } else {
                        actionResult.setSuccess(false);
                        actionResult.setMessage(errorInfo.getErrMsg());
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("模板消息异常："+e.getMessage());
            actionResult.setSuccess(false);
            actionResult.setMessage("模板消息异常："+e.getMessage());
        }finally {
            interfaceLogService.addLog(actionResult, IceFastJsonUtils.toJsonString(wechatTemplate), "/weChat/sendTemplateMessage", CommonConstant.INTERFACE_TYPE_SENDWECHATTEMPLATE);
        }
        return actionResult;
    }

    @Override
    public void sendTemplateMessage(String res) {
        ActionResult actionResult = new ActionResult();
        WechatTemplate wechatTemplate = null;
        try{
            if(IceStringUtils.isNoneBlank(res)){
                wechatTemplate = JSON.parseObject(res,WechatTemplate.class);
                if(wechatTemplate != null){
                    actionResult = sendTemplateMessage(wechatTemplate);
                }else{
                    actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                    actionResult.setMessage("模板消息为空");
                }
            }else{
                actionResult.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                actionResult.setMessage("模板消息为空");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("模板消息json转换失败："+e.getMessage());
            actionResult.setSuccess(false);
            actionResult.setMessage("模板消息json转换失败："+e.getMessage());

        }finally {
            interfaceLogService.addLog(actionResult, IceFastJsonUtils.toJsonString(wechatTemplate), "/weChat/sendTemplateMessage", CommonConstant.INTERFACE_TYPE_SENDWECHATTEMPLATE);
        }

    }

    private WechatTemplate templateMsg(String openid, boolean payResult, String amount, Date reqTime, String payResultMsg)
    {
        WechatTemplate template = new WechatTemplate();
        logger.info("payResult:"+payResult);
        String templateId=payResult?"CrDDEOZjQRqsdwrajlnt-6QsKwUS8obZRhciB6SPeVg":"tOv8zMLxiJl5Dx9mMSUrK80oyvbEPPjORnuZ1urQN8Y";
        String firstValue=payResult?"已成功发送提现请求！":"提现失败！失败原因："+payResultMsg+"。";
        String moneyKey=payResult?"money":"money";
        String timeKey=payResult?"timet":"time";
        template.setTemplateId(templateId);
        template.setAppId(CommonConstant.CONFIG_APPID);
        template.setOpenId(openid);
        template.setUrl("");
        First first = new First();
        first.setValue(firstValue);
        template.setFirst(first);
        KeyWord keyWordMoney = new KeyWord();
        keyWordMoney.setName(moneyKey);
        keyWordMoney.setValue(amount);
        KeyWord keyWordTime = new KeyWord();
        keyWordTime.setName(timeKey);
        keyWordTime.setValue(IceDateFormatUtils.dateToString(reqTime, "yyyy-MM-dd HH:mm:ss"));
        List<KeyWord> keyWords = new ArrayList<>();
        keyWords.add(keyWordMoney);
        keyWords.add(keyWordTime);
        template.setListKeyWord(keyWords);
        Remark remark = new Remark();
        remark.setValue("");
        template.setRemark(remark);
        return template;

    }
}
